﻿using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;

namespace rmTest.Common.UnityUtil
{
    public class UnityContext
    {

        /// <summary>
        /// 定义一个上下文
        /// </summary>
        private static IUnityContainer _unityContainerContext = null;
        private UnityContext()
        {

        }

        /// <summary>
        /// 初始化容器
        /// </summary>
        /// <param name="configPath"></param>
        /// <param name="nodeName"></param>
        /// <returns></returns>
        private static IUnityContainer InitContainner(string configPath, string nodeName)
        {
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + configPath);//找配置文件的路径
            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);

            IUnityContainer container = new UnityContainer();
            section.Configure(container, nodeName);
            return container;
        }

        public static IUnityContainer Instance
        {
            get
            {
                if (_unityContainerContext == null)
                {
                    _unityContainerContext = InitContainner("CfgFiles\\Unity.Config", "testContainerAop");
                }
                return _unityContainerContext;
            }
        }


        public static IUnityContainer GetInstance(string configPath, string nodeName)
        {
            if (_unityContainerContext == null)
            {
                _unityContainerContext = InitContainner(configPath, nodeName);
            }
            return _unityContainerContext;
        }
    }
}
